# -*- coding: utf-8 -*-

import cv2
import easyocr
from game import Square


class NumberRegResult:
    def __init__(self, x, y, w, h, img):
        self.left = x
        self.top = y
        self.right = x + w
        self.bottom = y + h
        self.width = w
        self.height = h
        self._value = ''
        self._img = img

    def set_number(self, number):
        self._value = number

    def get_number(self):
        return self._value

    def get_img(self):
        return self._img

    def remove_offset(self, x_offset, y_offset):
        self.left -= x_offset
        self.top -= y_offset
        self.right -= x_offset
        self.bottom -= y_offset

    def in_range(self, left, top, right, bottom):
        if self.left > left and self.top > top and self.right < right and self.bottom < bottom:
            return True
        else:
            return False

    def __str__(self):
        return 'number => ' + self._value + ' at [' + str(self.left) + ',' + str(self.top) + ',' + str(self.right) + ',' + str(self.bottom) + ']'


class Rect:
    def __init__(self, x, y, w, h, row, col):
        self.left = x
        self.top = y
        self.right = x + w
        self.bottom = y + h
        self.row = row
        self.col = col

    def __str__(self):
        return 'GameBoard Cell [' + str(self.row) + ',' + str(self.col) + ']=> [' + str(self.left) + ',' + str(self.top) + ',' + str(self.right) \
               + ',' + str(self.bottom) + ']'


class CVTool:
    def __init__(self, row, col):
        self.ext_rect_x = 0
        self.ext_rect_y = 0
        self.ext_rect_w = 0
        self.ext_rect_h = 0
        self.row = row
        self.col = col
        self.squares = []
        self.rectangles = []
        self.number_reg_results = []

    def init_square(self):
        self.squares = []
        for i in range(self.row):
            for j in range(self.col):
                self.squares.append(Square(i, j))

        delta_x = self.ext_rect_w / self.row
        delta_y = self.ext_rect_h / self.col

        for i in range(self.row):
            for j in range(self.col):
                x = j * delta_x
                y = i * delta_y
                w = delta_x
                h = delta_y

                rect = Rect(x, y, w, h, i, j)
                self.rectangles.append(rect)

    def find_square_location(self, number_pic):
        for rect in self.rectangles:
            if number_pic.in_range(rect.left, rect.top, rect.right, rect.bottom):
                # print(number_pic)
                # print(rect)
                return rect.row, rect.col
        return -1, -1

    def calculate_squares(self):
        for number_pic in self.number_reg_results:
            number_pic.remove_offset(self.ext_rect_x, self.ext_rect_y)
            row_index, col_index = self.find_square_location(number_pic)
            if row_index != -1 and col_index != -1:
                self.squares[row_index * self.col + col_index].set_value(number_pic.get_number())

    def parse_screen(self, pic_file_name):
        self.number_reg_results.clear()
        img = cv2.imread(pic_file_name)

        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        cv2.medianBlur(img_gray, 5)

        _, img_th = cv2.threshold(img_gray, 180, 255, cv2.THRESH_BINARY)
        cv2.medianBlur(img_th, 5)

        contours, _ = cv2.findContours(img_th, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

        max_x = max_y = max_w = max_h = 0
        max_area_size = 0

        for cnt in contours:
            x, y, w, h = cv2.boundingRect(cnt)

            area_size = w * h

            if area_size > max_area_size:
                max_area_size = area_size
                max_x = x
                max_y = y
                max_w = w
                max_h = h

            if 16000 < area_size < 48000:
                w = h = min(w, h)
                # print("x=" + str(x) + ", y=" + str(y) + ", w=" + str(w) + ",h=" + str(h))
                img_temp = img_gray[y:y + h, x:x + w]
                pic_number = NumberRegResult(x, y, w, h, img_temp)
                self.number_reg_results.append(pic_number)

        print('max rectangle = [' + str(max_x) + ',' + str(max_y) + ',' + str(max_w) + ',' + str(max_h) + ']')
        self.ext_rect_x = max_x
        self.ext_rect_y = max_y
        self.ext_rect_w = max_w
        self.ext_rect_h = max_h
        self.init_square()

        reader = easyocr.Reader(['en'])
        for pic in self.number_reg_results:
            number = reader.readtext(pic.get_img())
            pic.set_number(number[0][1])

        self.calculate_squares()
        return self.squares
